package com.xyxeshang.es.music.backend.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRules;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xyx-Eshang
 */
@Configuration      //高级的@Component注解，加入IOC容器的同时，还配置到注解中
@EnableSwagger2     //开启swagger2
public class SwaggerConfig {
	/**
	 * 你负责的这个Artifact的名字
	 */
	@Value("${PACKAGE_NAME}")
	String PACKAGE_NAME;

	@Value("${JWT_HEADER_NAME}")
	String JWT_HEADER_NAME;

	/**
	 * 01.设置一会儿要用于判断的环境
	 */
	Profiles profiles = Profiles.of("dev");

	/**
	 * 02.配置swagger文档的信息apiInfo
	 *
	 * @return
	 */
	private ApiInfo apiInfo() {
		//作者信息
		Contact contact = new Contact(
				//作者姓名
				"xyx-Eshang",
				//作者主页地址
				"localhost:80",
				//作者邮箱
				"xyx2112672663@163.com");

		return new ApiInfo(
				//文档标题
				"xyx-Eshang的SwaggerAPI文档",
				//文档描述
				"潜心静学，保持谦逊",
				//文档版本
				"v1.0",
				//使用协议的地址
				"xxx",
				//作者信息
				contact,
				//许可证
				"Apache 2.0",
				//许可证地址
				"http://www.apache.org/licenses/LICENSE-2.0",
				new ArrayList<>()
		);
	}

	/**
	 * 03.配置swagger的docket
	 * 参数environment表示当前的环境
	 *
	 * @param environment
	 * @return
	 */
	@Bean
	public Docket docket(Environment environment) {

		Docket docket = new Docket(DocumentationType.SWAGGER_2).
				apiInfo(apiInfo())
				//设置组名
				.groupName("xyx-Eshang")
				.enable(environment.acceptsProfiles(profiles))
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.xyxeshang." + PACKAGE_NAME + ".controller"))
				.build()
				.globalOperationParameters(getParameterList());
		docket.alternateTypeRules(AlternateTypeRules.newMapRule(String.class, List.class));
		return docket;
	}

	/**
	 * 04. 全局参数
	 *
	 * @return
	 */
	public List<Parameter> getParameterList() {
		ParameterBuilder token = new ParameterBuilder();
		List<Parameter> params = new ArrayList<>();
		token.name(JWT_HEADER_NAME)
				.description("令牌")
				.modelRef(new ModelRef("string"))
				.parameterType("header")
				.required(false)
				.build();
		params.add(token.build());
		return params;
	}
}